package com.zrrd.gmall.rabbit.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

//消息发送确认 确认消息到达了交换机
/*
*
* confirm 到了交换机
*
* returnedMessage 是没到队列 到了交换机
*
* */
@Slf4j
@Component
public class MQProductAckConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //修饰一个非静态方法 在构造后执行
    @PostConstruct
    public  void init(){
        //指定confirm
        rabbitTemplate.setConfirmCallback(this);
        //指定ReturnCallback
        rabbitTemplate.setReturnCallback(this);
    }
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack){
            log.info("消息发送成功===>"+ JSON.toJSONString(correlationData));
        } else {
            log.info("消息发失败===>原因"+
                    cause+"====>数据"+JSON.toJSONString(correlationData));
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode,
                                String replyText, String exchange, String routingKey) {
        System.out.println("消息主体"+new String(message.getBody()));
        System.out.println("应答码"+replyCode);
        System.out.println("描述"+replyText);
        System.out.println("对应交换机"+exchange);
        System.out.println("对应路由的键"+routingKey);
    }

}
